/**
 * 移动端瀑布流（关键）
 */
;(function() {
	'use strict';

	function WaterFull(ele, opts) {
		this.ele = this._selector(ele);
		this.conWidth = this.ele.offsetWidth;
		this.defaults = {
			positionLeft: '49%',
			timeout: 50,
			content: function (item, index) {
				return '';
			}
		};
		this.opts = this._extend({}, this.defaults, opts);
		this.first = true;
		this._init();
	}

	WaterFull.prototype = {

		_init: function() {
			this.ele.style.width = '100%';
			this.ele.style.position = 'relative';
			this.ele.style.overflow = 'hidden';
		},

		create: function(dataArr) {
			if (!dataArr.length) {
				return;
			}
			// 获取html
			var result = dataArr.map(this.opts.content);
			var ele = this.ele;

			ele.innerHTML += result.join('');

			var conWidth = this.conWidth;
			var positionLeft = this.opts.positionLeft;
			if (this.first) {
				this.first = false;
				setTimeout(function () {
					this.WaterFull.prototype.reflows(conWidth, ele, positionLeft);
				}, this.opts.timeout);
			} else {
				this.reflows(conWidth, ele, positionLeft);
			}

		},

		location: function() {
			this.first = false;
			this.reflows(this.conWidth, this.ele, this.opts.positionLeft);
		},
		// 定位
		reflows: function(conWidth, ele, positionLeft) {
			var itemList = Array.prototype.slice.call(ele.children),
				marginVal = conWidth * 0.02,
				columnHeightArr = [];

			itemList.forEach(function(item, index) {
				if (index < 2) {
					columnHeightArr[index] = item.offsetHeight + marginVal;
				} else {
					var minHeight = Math.min.apply(null, columnHeightArr),
						minHeightIndex = columnHeightArr.indexOf(minHeight);

					item.style.position = 'absolute';
					item.style.top = minHeight + 'px';

					if (minHeightIndex !== 0) {
						item.style.left = positionLeft;
					} else {
						item.style.left = '0';
					}

					columnHeightArr[minHeightIndex] += item.offsetHeight + marginVal;
				}
			});

			ele.style.minHeight = Math.max.apply(null, columnHeightArr) + 'px';
		},

		_extend: function() {
			var args = Array.prototype.slice.call(arguments),
				len = args.length,
				obj = null, i;

			for (i = 0; i < len; i ++) {
				if (typeof(args[i]) !== 'object') {
					break;
				}
				if (i !== 0) {
					for (var o in args[i]) {
						if (args[i].hasOwnProperty(o)) obj[o] = args[i][o];
					}
				} else {
					obj = args[0];
				}
			}

			return obj;
		},

		_selector: function(ele) {
			if (!ele) {
				return;
			}
			return document.querySelector(ele);
		}
	};

	window.WaterFull = WaterFull;

})();

//waterfull AMD Export

if (typeof module !== 'undefined') {
	module.exports = window.WaterFull;
} else if (typeof define === 'function' && define.amd) {
    define([], function () {
        'use strict';
        return window.WaterFull;
    });
}